package cn.tedu.bonfire.admin.content.service.impl;

import cn.tedu.bonfire.admin.content.dao.persist.repository.ITagAndNoteRepository;
import cn.tedu.bonfire.admin.content.dao.persist.repository.ITagRepository;
import cn.tedu.bonfire.admin.content.dao.search.impl.TagElasticsearchRepositoryImpl;
import cn.tedu.bonfire.admin.content.pojo.dto.AddNewTagDTO;
import cn.tedu.bonfire.admin.content.pojo.entity.Tag;
import cn.tedu.bonfire.admin.content.pojo.vo.TagListStartVO;
import cn.tedu.bonfire.admin.content.service.ITagService;
import cn.tedu.bonfire.common.enumerator.ServiceCode;
import cn.tedu.bonfire.common.ex.ServiceException;
import cn.tedu.bonfire.common.pojo.po.TagAdminSearchPO;
import cn.tedu.bonfire.common.pojo.vo.PageData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TagServiceImpl implements ITagService {

    @Autowired
    private ITagRepository tagRepository;
    @Value("${bonfire.dao.default-query-page-size}")
    private Integer defaultQueryPageSize;
    @Autowired
    private ITagAndNoteRepository tagAndNoteRepository;
    @Autowired
    private TagElasticsearchRepositoryImpl tagElasticsearchRepository;

    @Override
    public void annNew(AddNewTagDTO addNewTagDTO) {
        List<String> tagNames = addNewTagDTO.getTagName();
        for(String tagName : tagNames){
            Tag tag = new Tag();
            Integer count = Math.toIntExact(tagRepository.countByTagName(tagName));
            if(count > 0){
                String message = "添加标签失败，标签已存在";
                throw new ServiceException(ServiceCode.ERROR_CONFLICT,message);
            }
            tag.setTagName(tagName);
            tag.setAuditStatus(1);
            tagRepository.insert(tag);
        }
    }

    @Override
    public void deleteTagById(Long id) {
        tagAndNoteRepository.deleteTagById(id);
        tagRepository.deleteTagById(id);
    }

    @Override
    public void updateTagNameById(Long id, String tagName) {
        tagRepository.updateTagNameById(id,tagName);
    }

    @Override
    public PageData<TagListStartVO> list(Integer pageNum) {
        return tagRepository.list(pageNum,defaultQueryPageSize);
    }

    @Override
    public void rebuildSearch() {
        Integer pageNum = 1;
        Integer pageSize = 10;
        Integer maxPage;
        do{
            PageData<TagAdminSearchPO> pageData = tagRepository.listSearchByOrder(pageNum, pageSize);
            maxPage = pageData.getMaxPage();
            tagElasticsearchRepository.saveAll(pageData.getList());
            pageNum++;
        }while (pageNum <= maxPage);
    }

    @Override
    public PageData<TagListStartVO> search(String keyword, Integer pageNum) {
        return null;
    }
}
